package com.sise.rsc.websocket;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 类似RequestMapping的地址
 * ws://localhost:8080/ws/000001
 */
@ServerEndpoint("/ws/{uuid}")
@Component
public class WebSocketService {

    private Session session; //客户端会话

    public Session getSession() {
        return session;
    }

    //存放每个客户端的连接会话
    public static ConcurrentHashMap<String,WebSocketService> clients = new ConcurrentHashMap<>();

    //开启连接
    //存入连接回话中
    @OnOpen
    public void onOpen(Session session, @PathParam( "uuid") String uuid){
        System.out.println("当前的uuid为："+uuid);
        this.session = session;
        clients.put(uuid,this);
    }

    //发送消息
    @OnMessage
    public void OnMessage(String msg, @PathParam( "uuid") String uuid){
        System.out.println("当前的uuid为："+uuid);
        System.out.println("收到消息: "+msg);
    }

    //关闭连接
    @OnClose
    public void onClose(@PathParam( "uuid") String uuid){
        System.out.println("当前的uuid为："+uuid);
        System.out.println("关闭socket连接"+uuid);
        clients.remove(uuid);
    }
    //发生异常的情况
    @OnError
    public void onError(Throwable error) {
        error.printStackTrace();
    }

}
